<template>
	<div id="user-login-view">
		<h2 class="title">Tao牌共享图库网 - 登录</h2>
		<div class="desc">企业级智能协同云图库</div>
		<a-form :model="formState" name="basic" autocomplete="off" @finishFailed="onFinishFailed">
			<a-form-item name="userAccount" :rules="[{ required: true, message: '请输入账号!' }]">
				<a-input v-model:value="formState.userAccount" placeholder="请输入账号" />
			</a-form-item>

			<a-form-item
				name="userPassword"
				:rules="[
					{ required: true, message: '请输入密码!' },
					{ min: 8, message: '密码长度不能少于8位!' },
				]"
			>
				<a-input-password v-model:value="formState.userPassword" placeholder="请输入密码" />
			</a-form-item>

			<div class="tips">
				没有账号？
				<router-link to="/user/register">立即注册</router-link>
			</div>

			<a-form-item>
				<a-button type="primary" html-type="submit" style="width: 100%" @click="handleSubmit(formState)">登录</a-button>
			</a-form-item>
		</a-form>
	</div>
</template>
<script setup lang="ts">
import router from '@/router'
import { userLoginUsingPost } from '@/api/userController'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import { message } from 'ant-design-vue'
import { reactive } from 'vue'
import { useRoute } from 'vue-router'

// 用户表单数据类型定义
const formState = reactive<API.UserLoginRequest>({
	userAccount: '',
	userPassword: '',
})

const loginUserStore = useLoginUserStore()
const route = useRoute()

// 表单验证失败处理
const onFinishFailed = (errorInfo: any) => {
	// console.log('表单验证失败:', errorInfo)
}

// 提交表单
const handleSubmit = async (values: API.UserLoginRequest) => {
	try {
		const res = await userLoginUsingPost(values)
		if (res.data.code === 0 && res.data.data) {
			// 显示成功消息
			message.success('登录成功！')

			// 先更新用户信息
			await loginUserStore.fetchLoginUser()

			// 稍微延迟后进行跳转，确保状态更新完成
			setTimeout(() => {
				// 获取重定向URL并清理
				let redirectPath = (route.query.redirect as string) || '/'

				// 清理可能的URL重复拼接问题
				if (redirectPath.startsWith('http://') || redirectPath.startsWith('https://')) {
					try {
						const url = new URL(redirectPath)
						redirectPath = url.pathname + url.search + url.hash
					} catch {
						redirectPath = '/'
					}
				}

				// 确保路径以 / 开头
				if (!redirectPath.startsWith('/')) {
					redirectPath = '/' + redirectPath
				}

				router.replace(redirectPath)
			}, 200)
		} else {
			// 处理后端返回的错误
			message.error(res.data.message || '登录失败')
		}
	} catch (error) {
		message.error('登录失败：' + (error instanceof Error ? error.message : String(error)))
		return
	}
}
</script>

<style scoped lang="scss">
#user-login-view {
	max-width: 360px;
	margin: 0 auto;

	.title {
		text-align: center;
		margin-bottom: 16px;
	}

	.desc {
		text-align: center;
		color: #bbb;
		margin-bottom: 16px;
	}

	.tips {
		color: #bbb;
		text-align: right;
		font: 13px;
		margin-bottom: 16px;
	}
}
</style>
